package com.zjff.show.zjffshow;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;

import java.nio.charset.StandardCharsets;
import java.util.List;

@Configuration //说明是Spring的配置类
public class APIConfigurationSupport extends WebMvcConfigurationSupport {//继承MVC的拦截器配置
    //把自定义的拦截器注入到Spring容器,在Service层就可以使用@Autowired注入
    @Bean
    public APIInterceptions apiInterceptions(){//新建对象并注入

        return new APIInterceptions();
    }
    @Override
    protected  void addCorsMappings(CorsRegistry registry){
        registry.addMapping("/**")
                .allowedOriginPatterns("*")
                .allowedMethods("GET","HEAD","POST","PUT","DELETE","OPTIONS")
                .allowCredentials(true)
                .maxAge(3600)
                .allowedHeaders("*");
    }
    @Override
    protected void addInterceptors(InterceptorRegistry registry){
        //添加拦截器到框架
        //addPathPatterns是需要拦截的路径
        //excludePathPatterns不需要拦截的路径
        registry.addInterceptor(apiInterceptions()).addPathPatterns("/**").excludePathPatterns("/Img/**");
        super.addInterceptors(registry);
    }
    //解决乱码
    @Override
    protected void extendMessageConverters(List<HttpMessageConverter<?>> converters){
        for (HttpMessageConverter<?> converter:converters){
            if (converter instanceof StringHttpMessageConverter){
                ((StringHttpMessageConverter)converter).setDefaultCharset(StandardCharsets.UTF_8);
            }
        }
    }
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry){
        registry.addResourceHandler("/Img/**").addResourceLocations("file:D:\\image\\");
    }

}
